//
//  ShoppingCarAlertModifyView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/3.
//

import UIKit
import RxSwift

typealias ShoppingCarAlertModifyViewCallBack = (NSInteger, NSInteger)->()

class ShoppingCarAlertModifyView: UIView {
    var callBack: ShoppingCarAlertModifyViewCallBack!
    var contentView: UIView!
    var bkgBtnView: UIButton!
    var titleStr: String = ""
    var btnTitleArray: [String] = []
    var lineView1: UIView!
    var titleLab: UILabel!
    var textField: UITextField! //输入框
    var minBtn: UIButton!  //减
    var addBtn: UIButton! //加
    var number: NSInteger = 1 {
        didSet {
            if self.number >= self.maxNumber {
                self.warnLab?.isHidden = false
                self.warnLab?.text = String(format: "最大限购数为 %d", self.maxNumber)
                self.addBtn?.setup_image(image: UIImage.init(named: "icon_add_gray1"))
            }else if self.number <= self.minNumber  {
                self.minBtn?.setup_image(image: UIImage.init(named: "icon_min_gray"))
            }else{
                self.addBtn?.setup_image(image: UIImage.init(named: "icon_add_black1"))
                self.minBtn?.setup_image(image: UIImage.init(named: "icon_min_black"))
                self.warnLab?.isHidden = true
            }
            self.updateConstraints()
        }
    }  //输入数量
    var minNumber: NSInteger = 1 //最小值
    var maxNumber: NSInteger = 9999999 //限购
    var warnLab: UILabel! //警告提示
    
    var dis = DisposeBag()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
     }
    
    func setupUI(){
        self.bkgBtnView = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        self.bkgBtnView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.65)
        self.bkgBtnView.alpha = 0
        self.addSubview(self.bkgBtnView)

        self.contentView = UIView.init(frame: CGRect.init(x: 46, y: 280, width: kScreenWidth - 92, height: 125))
        self.contentView.backgroundColor = UIColor.white
        self.contentView.layer.cornerRadius = 10
        self.contentView.layer.masksToBounds = true
        self.bkgBtnView.addSubview(self.contentView)

        //标题
        self.titleLab = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: self.contentView.frame.size.width, height: 14))
        self.titleLab.backgroundColor = UIColor.clear
        self.titleLab.textAlignment = .center
        self.titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.titleLab.textColor = Theme.titleLabColor
        self.titleLab.text = self.titleStr
        self.contentView.addSubview(self.titleLab)

        self.textField = UITextField.init(frame: CGRect.init(x: 15, y: self.titleLab.frame.maxY, width: 88, height: 40))
        self.textField.backgroundColor = UIColor.clear
        self.textField.textColor = Theme.titleLabColor
        self.textField.textAlignment = .center
        self.textField.layer.borderWidth = 0.5
        self.textField.layer.borderColor = Theme.lightNineColor.cgColor
        self.textField.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        self.textField.leftViewMode = .always
        self.textField.rightViewMode = .always
        self.textField.keyboardType = .numberPad
        self.textField.text = "\(self.number)"
        self.textField.delegate = self
        self.textField.becomeFirstResponder()
        self.contentView.addSubview(self.textField)

        self.warnLab = UILabel.init()
        self.warnLab.backgroundColor = UIColor.clear
        self.warnLab.textAlignment = .center
        self.warnLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 12)
        self.warnLab.textColor = Theme.redColor
        self.contentView.addSubview(self.warnLab)

        //减
        self.minBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
        self.minBtn.setImage(UIImage.init(named: "icon_min_black"), for: .normal)
        self.minBtn.setImage(UIImage.init(named: "icon_min_black"), for: .highlighted)
        self.minBtn.rightBorder(width: 0.5, borderColor: Theme.lightNineColor)
        self.minBtn.addTarget(self, action: #selector(minBtnAction), for: .touchUpInside)
        self.contentView.addSubview(self.minBtn)
        //加
        self.addBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
        self.addBtn.setImage(UIImage.init(named: "icon_add_black1"), for: .normal)
        self.addBtn.setImage(UIImage.init(named: "icon_add_black1"), for: .highlighted)
        self.addBtn.leftBorder(width: 0.5, borderColor: Theme.lightNineColor)
        self.addBtn.addTarget(self, action: #selector(addBtnAction), for: .touchUpInside)
        self.contentView.addSubview(self.addBtn)

        ///线条
        self.lineView1 = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.contentView.frame.size.width, height: 0.5))
        self.lineView1.backgroundColor = UIColor.init(hex: 0xE1E3E6, alpha: 1)
        self.contentView.addSubview(self.lineView1)
        self.addsnpLayout()
        self.addAlertBtn2()

        self.textField.rx.text.orEmpty.subscribe { txt in
            self.warnLab.isHidden = true
            if self.textField.text != "" {
                let tempNumber = NSInteger(self.textField.text!)!
                if tempNumber > self.maxNumber {
                    self.number = self.maxNumber
                }else if tempNumber < self.minNumber {
                    self.number = self.minNumber
                }else{
                    self.number = tempNumber
                }
                self.textField.text = "\(self.number)"
            }else{
                self.textField.text = "\(self.number)"
                self.number = self.minNumber
            }
        }.disposed(by: self.dis)

        self.startAnimation()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
//
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        self.startAnimation()
//    }
    
    //开始动画
    func startAnimation(){
        self.bkgBtnView.alpha = 0
        UIView.animate(withDuration: 0.24) {
            self.bkgBtnView.alpha = 1
        }
    }
    
    ///关闭
    func dismissAlertView(){
        self.bkgBtnView.alpha = 1
        UIView.animate(withDuration: 0.24, animations: {
            self.bkgBtnView.alpha = 0
        }) { (flag) in
//            self.dismiss(animated: false, completion: nil)
            self.removeFromSuperview()
        }
    }
    
    ///两个按钮
    func addAlertBtn2() {
        let btn1Title = self.btnTitleArray[0]
        let btn1 = UIButton.init(frame: CGRect.init(x: 0, y: self.lineView1.frame.maxY, width: self.contentView.frame.size.width/2-0.25, height: 49))
        btn1.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
        btn1.setTitleColor(Theme.line8Color, for: .normal)
        btn1.setTitleColor(Theme.line8Color, for: .highlighted)
        btn1.setTitle(btn1Title, for: .normal)
        btn1.setTitle(btn1Title, for: .highlighted)
        btn1.addTarget(self, action: #selector(btn1Action), for: .touchUpInside)
        self.contentView.addSubview(btn1)
        
        
        let btn2Title = self.btnTitleArray[1]
        let btn2 = UIButton.init(frame: CGRect.init(x: btn1.frame.maxX, y: self.lineView1.frame.maxY, width: self.contentView.frame.size.width/2-0.25, height: 49))
        btn2.leftBorder(width: 0.5, borderColor: UIColor.init(hex: 0xE1E3E6, alpha: 1))
        btn2.frame = CGRect.init(x: btn1.frame.maxX, y: 0, width: self.contentView.frame.size.width/2, height: 49)
        btn2.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
        btn2.setTitleColor(Theme.mainColor, for: .normal)
        btn2.setTitleColor(Theme.mainColor, for: .highlighted)
        btn2.setTitle(btn2Title, for: .normal)
        btn2.setTitle(btn2Title, for: .highlighted)
        btn2.addTarget(self, action: #selector(btn2Action), for: .touchUpInside)
        self.contentView.addSubview(btn2)
        
        btn1.snp.makeConstraints { (make) in
            make.left.equalTo(self.contentView.snp.left).offset(0)
            make.width.equalTo(self.contentView.frame.size.width/2)
            make.height.equalTo(49)
            make.top.equalTo(self.lineView1.snp.bottom)
        }
        
        btn2.snp.makeConstraints { (make) in
            make.top.equalTo(self.lineView1.snp.bottom)
            make.left.equalTo(btn1.snp.right).offset(0)
            make.width.equalTo(self.contentView.frame.size.width/2)
            make.height.equalTo(49)
            make.bottom.equalTo(self.contentView.snp.bottom)
        }
    }
    
    ///关闭按钮
    @objc func btn1Action(){
        self.textField.resignFirstResponder()
        if self.callBack != nil {
            self.callBack(0, self.number)
            self.dismissAlertView()
        }
    }
    
    ///确定按钮
    @objc func btn2Action(){
        self.textField.resignFirstResponder()
        var tempNumber: NSInteger = 0
        if textField.text != "" {
            tempNumber = NSInteger(textField.text ?? "1")!
        }

        if tempNumber < self.minNumber {
            self.warnLab.text = String(format: "最小起购数为 %d", self.minNumber)
            return
        }
        
        if tempNumber > self.maxNumber {
            self.warnLab.text = String(format: "最大限购数为 %d", self.maxNumber)
            return
        }
        
        if self.callBack != nil {
            self.callBack(1, tempNumber)
            self.dismissAlertView()
        }
    }
    
    ///减数量
    @objc func minBtnAction(){
        self.textField.resignFirstResponder()
        if self.number <= self.minNumber {
            if self.minNumber > 0 {
                self.warnLab.isHidden = false
                self.warnLab.text = String(format: "最小起购数为 %d", self.minNumber)
            }
            return
        }
        self.number = self.number - 1
        self.textField.text = "\(self.number)"
        self.textField.sendActions(for: .allEvents)
    }
    
    ///加数量
    @objc func addBtnAction(){
        self.textField.resignFirstResponder()
        if self.number >= self.maxNumber {
            self.warnLab.isHidden = false
            self.warnLab.text = String(format: "最大限购数为 %d", self.maxNumber)
            return
        }
        self.number = self.number + 1
        self.textField.text = "\(self.number)"
        self.textField.sendActions(for: .allEvents)
    }
    
    ///布局
    func addsnpLayout() {
        self.bkgBtnView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalTo(0)
        }
        
        self.contentView.snp.makeConstraints { (make) in
            make.left.equalTo(self.bkgBtnView.snp.left).offset(46)
            make.right.equalTo(self.bkgBtnView.snp.right).offset(-46)
            make.top.equalTo(self.bkgBtnView.snp.top).offset(280)
        }
        
        self.titleLab.snp.makeConstraints { (make) in
            make.left.equalTo(self.contentView.snp.left).offset(0)
            make.right.equalTo(self.contentView.snp.right).offset(0)
            make.top.equalTo(self.contentView.snp.top).offset(20)
            make.height.equalTo(14)
        }
        
        self.minBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.contentView.snp.left).offset(73)
            make.top.equalTo(self.titleLab.snp.bottom).offset(16)
            make.size.equalTo(CGSize.init(width: 30, height: 30))
        }
        
        self.addBtn.snp.makeConstraints { (make) in
            make.right.equalTo(self.contentView.snp.right).offset(-73)
            make.top.equalTo(self.titleLab.snp.bottom).offset(16)
            make.size.equalTo(CGSize.init(width: 30, height: 30))
        }
        
        self.textField.snp.makeConstraints { (make) in
            make.left.equalTo(self.minBtn.snp.left).offset(0)
            make.right.equalTo(self.addBtn.snp.right).offset(0)
            make.top.equalTo(self.titleLab.snp.bottom).offset(16)
            make.height.equalTo(30)
        }
        
        warnLab.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(textField.snp.bottom).offset(8)
        }
        
        self.lineView1.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(0.5)
            make.top.equalTo(self.warnLab.snp.bottom).offset(10)
        }
    }
    
    
    
}

extension ShoppingCarAlertModifyView: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var isValid = true
        let len = string.count
        if len > 0 {
            let numberRegex = "^[0-9]"
            let numberPredicate = NSPredicate.init(format: "SELF MATCHES %@", numberRegex)
            isValid = numberPredicate.evaluate(with: string)
        }
        return isValid
    }
}
